<template>
  <div class="login-container">
    <div class="login-box">      <div class="login-header">
        <h1>智能空气质检仪</h1>
        <h2>管理系统</h2>
        <div class="company">智慧环境技术有限公司</div>
      </div><div class="login-form">
        <el-form ref="formRef" :model="loginForm" :rules="loginRules" label-position="top">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="loginForm.username" placeholder="请输入用户名">
              <template #prefix>
                <el-icon><User /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input 
              v-model="loginForm.password" 
              type="password" 
              placeholder="请输入密码"
              @keyup.enter="handleLogin"
            >
              <template #prefix>
                <el-icon><Lock /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-checkbox v-model="loginForm.rememberMe">记住我</el-checkbox>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :loading="loading" class="login-button" @click="handleLogin">
              登录系统
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import { defineComponent, reactive, ref } from 'vue';
import { User, Lock } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import { login } from '../api/user';

export default defineComponent({
  components: { User, Lock },
  name: 'LoginView',
  setup() {
    const router = useRouter();
    const loginForm = reactive({
      username: '',
      password: '',
      rememberMe: false
    });

    const loginRules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '用户名长度应在3-20个字符之间', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '密码长度应在6-20个字符之间', trigger: 'blur' }
      ]
    };
    
    const loading = ref(false);
    const formRef = ref(null);
      const handleLogin = () => {
      if (formRef.value) {
        formRef.value.validate(valid => {
          if (valid) {
            loading.value = true;
            // 调用登录API
            login({
              username: loginForm.username,
              password: loginForm.password
            })              .then(response => {
                console.log('登录响应:', response);
                if (response && response.data && response.data.token) {
                  // 确保存储格式正确的身份验证令牌
                  const token = response.data.token;
                  // 存储标准格式的Bearer token
                  localStorage.setItem('token', `Bearer ${token}`);
                  
                  // 对token进行解析和验证
                  try {
                    const tokenParts = token.split('.');
                    if (tokenParts.length === 3) {
                      const payload = JSON.parse(atob(tokenParts[1]));
                      console.log('Token payload:', payload);
                      console.log('Token过期时间:', new Date(payload.exp * 1000).toLocaleString());
                      
                      // 存储token过期时间
                      localStorage.setItem('tokenExpires', payload.exp * 1000);
                    }
                  } catch (e) {
                    console.error('Token解析失败:', e);
                  }
                  
                  // 存储用户信息
                  if (response.data.userInfo) {
                    localStorage.setItem('userId', response.data.userInfo.id);
                    localStorage.setItem('userInfo', JSON.stringify(response.data.userInfo));
                  }
                  
                  if (loginForm.rememberMe) {
                    localStorage.setItem('rememberedUser', loginForm.username);
                  } else {
                    localStorage.removeItem('rememberedUser');
                  }
                  
                  ElMessage.success('登录成功，正在跳转...');
                  
                  // 跳转到仪表盘
                  router.push('/dashboard');
                } else {
                  ElMessage.error('用户名或密码错误');
                }
              })
              .catch(error => {
                console.error('登录失败:', error);
                ElMessage.error('登录失败，请稍后再试');
              })
              .finally(() => {
                loading.value = false;
              });
          } else {
            return false;
          }
        });
      }
    };
    
    return {
      loginForm,
      loginRules,
      loading,
      formRef,
      handleLogin
    };
  }
});
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: linear-gradient(135deg, #43cea2 0%, #185a9d 100%);
}

.login-box {
  width: 400px;
  padding: 30px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-header h1 {
  color: #409EFF;
  font-weight: 600;
  margin-bottom: 5px;
  font-size: 28px;
}

.login-header h2 {
  color: #409EFF;
  font-weight: 600;
  margin-bottom: 10px;
  font-size: 22px;
}

.login-header .company {
  color: #888;
  font-size: 14px;
}

.login-button {
  width: 100%;
  padding: 12px 0;
  font-size: 16px;
}

.el-form-item {
  margin-bottom: 20px;
}
</style>
